import {C, getImageData} from '../utils'

let mouse_s = {x:0, y:0, down: false}
let mouse = {};
let item = null;
let _this = null;

function start(e){
  let {x, y} = C.eventWrapper(e, _this.scale)
  mouse_s.x = x;
  mouse_s.y = y;
  mouse_s.down = true;
  _this.imgData = getImageData(_this.canvas);
}
function move(ctx, width, height, color, lineWidth, imgData){
  let x = mouse_s.x;
  let y = mouse_s.y;
  let w = mouse.x - mouse_s.x;
  let h = mouse.y - mouse_s.y;
  ctx.clearRect(0, 0, width, height)
  ctx.putImageData(imgData, 0, 0)
  ctx.strokeStyle = color
  ctx.lineWidth = lineWidth
  ctx.strokeRect(x, y , w, h)
  item = {type: 'Square', x, y, w, h, ys: color, xw: lineWidth}
}

function end(){
  if(!mouse_s.down)return;
  if(item){
    _this.save(item);
  }
  mouse_s.down = false;
  item = null;
}

export default {
  click(){
    _this = this;
    mouse = C.getOffset(this.canvas, this.scale)
    this.disabledCtrl('Rotate', true)
  },
  canvasMousedown(e){
    start(e)
  },
  canvasMouseup(){},
  canvasMouseout(){},
  canvasTouchstart(e){
    let target = e.target;
    if(e.changedTouches && e.changedTouches.length > 0){
      e = e.changedTouches[0]
      start({pageX: e.pageX, pageY: e.pageY, target})
    }
  },
  canvasTouchend(){},
  winMouseup(){
    end()
  },
  winMousemove(){
    if(!mouse_s.down)return;
    const {color, lineWidth} = this.defDrawOptions
    const {width, height} = this.canvasRect
    move(this.ctx, width, height, color, lineWidth, this.imgData)
  },
  winTouchMove(e){
    if(!mouse_s.down)return;
    let target = e.target;
    const {color, lineWidth} = this.defDrawOptions
    const {width, height} = this.canvasRect
    if(e.changedTouches && e.changedTouches.length > 0){
      e = e.changedTouches[0]
      mouse = C.eventWrapper({pageX: e.pageX, pageY: e.pageY, target})
      move(this.ctx, width, height, color, lineWidth, this.imgData)
    }
  },
  winTouchend(){
    end()
  },
  visibilitychange(){}
}
